﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class Game : PersistableObject {
    public PersistableObject prefab;
    private PersistentStorage storage;
    public KeyCode creatkey = KeyCode.C;
    public KeyCode newGame = KeyCode.N;
    public KeyCode save = KeyCode.S;
    public KeyCode load = KeyCode.L;
    List<PersistableObject> objlist = new List<PersistableObject> ();
    string savePath;

    private void Awake () {
        savePath = Path.Combine (Application.persistentDataPath, "saveFile");
        storage = GetComponent<PersistentStorage> ();
    }
    private void Update () {
        if (Input.GetKeyDown (creatkey)) {
            CreatObject ();
        }
        if (Input.GetKeyDown (newGame)) {
            BeginNew ();
        }
        if (Input.GetKeyDown (save)) {
            storage.Save (this);
        }
        if (Input.GetKeyDown (load)) {
            BeginNew ();
            storage.Load (this);
        }
    }
    private void CreatObject () {
        var o = Instantiate (prefab);
        var t = o.transform;
        t.localPosition = Random.insideUnitCircle * 5f;
        t.localRotation = Random.rotation;
        t.localScale = Random.Range (0.1f, 1) * Vector3.one;
        objlist.Add (o);
    }
    void BeginNew () {
        for (int i = 0; i < objlist.Count; i++) {
            Destroy (objlist[i].gameObject);
        }
        objlist.Clear ();
    }

    public override void Save (GameDataWriter writer) {
        writer.Write (objlist.Count);
        foreach (var i in objlist) {
            i.Save (writer);
        }
        Debug.Log ("保存完毕");
    }

    public override void Load (GameDataRead reader) {
        int count = reader.ReadInt ();
        for (int i = 0; i < count; i++) {
            var o = Instantiate (prefab);
            o.Load (reader);
            objlist.Add (o);
        }
        Debug.Log ("加载完毕");
    }
}